/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: UISafeKeeper.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.baselib.network.response;

import android.os.Handler;

import io.bhex.baselib.mvp.BaseUI;

/**
 * 添加了对UI状态的判断,进行防御
* ================================================
* 作   者：ppzhao
* 创建时间：2018/5/31
* 邮   箱：
* 描   述：
* ================================================
*/
public class UISafeKeeper<T> implements ResponseListener<T> {
    private BaseUI ui;

    private ResponseListener<T> innerListener;

    private UISafeKeeper(BaseUI ui, ResponseListener<T> listener) {
        this.ui = ui;
        this.innerListener = listener;
    }

    @Override
    public void onBefore() {
        if (ui == null || !ui.isAlive())
            return;

        innerListener.onBefore();
    }

    @Override
    public void onFinish() {
        if (ui == null || !ui.isAlive())
            return;

        innerListener.onFinish();
    }

    @Override
    public void onSuccess(T response) {
        if (ui == null || !ui.isAlive())
            return;

        innerListener.onSuccess(response);
    }

    @Override
    public void onError(Throwable error) {
        if (ui == null || !ui.isAlive())
            return;

        innerListener.onError(error);
    }

    @Override
    public void onAfter() {
        if (ui == null || !ui.isAlive())
            return;

        innerListener.onAfter();
    }

    @Override
    public T parserResponse(Handler uiHandler, String response, Class<T> clazz) {
        return innerListener.parserResponse(uiHandler, response, clazz);
    }

    public static final <C> ResponseListener guard(BaseUI ui, ResponseListener<C> listener) {
        return new UISafeKeeper<C>(ui, listener);
    }
}
